package com.reporting.yb.framework.common.util.wechatlogin;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WeChatApiUtil {

    private static final String APP_ID = "wxc83c8ebc8692439f";
    private static final String APP_SECRET = "aa91761f542a7dc9c5794b956151d09a";
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static final RestTemplate restTemplate = new RestTemplate();

    public static WeChatLoginResult getOpenIdByCode(String code) {
        String url = WX_LOGIN_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());

        if (jsonObject.getInteger("errcode") != null) {
            return null;
        }

        WeChatLoginResult result = new WeChatLoginResult();
        result.setOpenid(jsonObject.getString("openid"));
        result.setSessionKey(jsonObject.getString("session_key"));

        return result;
    }

    public static class WeChatLoginResult {
        private String openid;
        private String sessionKey;

        // getters and setters

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getSessionKey() {
            return sessionKey;
        }

        public void setSessionKey(String sessionKey) {
            this.sessionKey = sessionKey;
        }
    }
}